<?php

class StudentTransfer_ReinController extends Zend_Controller_Action
{
    //TODO 畫面調整
    private $_teacherSn;
    public function init()
    {
        /* Initialize action controller here */
        $this->_teacherSn = Teacher_Model_Teacher::getSnById($this->view->user->username);
    }

    public function indexAction()
    {
        $form = new StudentTransfer_Form_Rein() ;
        //取系統預設值
        $param = new Default_Model_ModulesParam();
        $param_arr = $param->getParamByResourceId('student');

        $form->setDefault('approve_organ',$param_arr['default_approve_organ']);
        $form->setDefault('approve_word',$param_arr['default_approve_word']);
        $form->setDefault('causation',$param_arr['default_causation_out']);

        $this->view->form = $form;
    }

    public function reinSetAction()
    {
        $data  = $this->getRequest()->getParams();
        $data['rein']['year'] = $this->view->Semester['year'];
        $data['rein']['semester'] = $this->view->Semester['semester'];
        //        print_r($data); exit;
        $form = new StudentTransfer_Form_Rein();
        if ($form->isValid($data)){
            $row = $data['rein'];

            // 取出 student_sn
            $q = Doctrine_Query::create()
            ->select('student_sn')
            ->from('Student_Model_StudentTransfer')
            ->where('sn=?', $row['sn']);
            $trRow = $q->fetchOne(null,Doctrine_Core::HYDRATE_ARRAY);
            //print_r($trRow); exit;

            // 更改就學狀態
            $q = Doctrine_Query::create()
            ->update('Student_Model_Student')
            ->set('study_condition','?',Student_Model_StudentTransfer::IN_STADY)
            ->where('sn=?', $trRow['student_sn']);
            $q->execute();
            // 加入學期設定
            $q = Doctrine_Query::create()
            ->select('sn')
            ->from('Student_Model_StudentSemester')
            ->where('year=?', $row['year'])
            ->andWhere('semester=?', $row['semester'])
            ->andWhere('student_id=?', $row['student_id']);
            $res = $q->fetchOne();

            $studentSemester = new Student_Model_StudentSemester();
            if ($res) {
                $studentSemester->assignIdentifier($res->sn);
            }
            $studentSemester->year = $row['year'];
            $studentSemester->semester = $row['semester'];
            $studentSemester->student_sn = $trRow['student_sn'];
            $studentSemester->student_id = $row['student_id'];
            $tempArr = explode("-", $row['selClass']);
            $studentSemester->grade = (int)$tempArr[0];
            $studentSemester->class_sn = (int)$tempArr[1];
            $studentSemester->number = $row['number'];
            $studentSemester->save();


            // teacher_sn
            $teacherSn = $this->_teacherSn;

            // 加入復學記錄
            $studentTransfer = new Student_Model_StudentTransfer();
            $studentTransfer->year = $row['year'];
            $studentTransfer->semester = $row['semester'];
            $studentTransfer->causation_kind = $row['causation_kind'];
            $studentTransfer->student_sn = $trRow['student_sn'];
            $studentTransfer->date = $row['date'];
            $studentTransfer->approve_organ = $row['approve_organ'];
            $studentTransfer->approve_date = $row['approve_date'];
            $studentTransfer->approve_word = $row['approve_word'];
            $studentTransfer->approve_number = $row['approve_number'];
            $studentTransfer->teacher_sn = $teacherSn;
            $studentTransfer->save();

            $this->_helper->json(1);
        }
        else
        $this->_helper->json(array('error'=>$form->getMessages()));
    }

    /**
     * 復學資料修改
     * @return unknown_type
     */
    public function reinEditAction()
    {
        $data  = $this->getRequest()->getParams();
        $data['rein']['year'] = $this->view->Semester['year'];
        $data['rein']['semester'] = $this->view->Semester['semester'];
        $form = new StudentTransfer_Form_Rein();
        if ($form->isValid($data)) {
            $dataRein = $data['rein'];
            $teacherSn = $this->_teacherSn;
            $dataRein['teacher_sn'] = $teacherSn;
            $studentTransfer = new Student_Model_StudentTransfer();
            $studentTransfer->assignIdentifier($dataRein['sn']);
            unset($dataRein['student_sn']);
            $studentTransfer->fromArray($dataRein);
            $studentTransfer->save();

            $this->_helper->json(1);
        }
        else
        $this->_helper->json(array('error'=>$form->getMessages()));
    }

    /**
     * 取出 學期轉入學生資料
     * @return unknown_type
     */
    public function getStudentAction()
    {
        $this->getHelper('layout')->disableLayout();
        $request = $this->getRequest();
        if ($request->getParam('year_semester')) {
            $arr = explode("-",$request->getParam('year_semester'));
            $year = (int)$arr[0];
            $semester =(int) $arr[1];
        }
        else {
            $year = $this->view->Semester['year'];
            $semester = $this->view->Semester['semester'];
        }
        $kind = $request->getParam('kind');
        $q = Doctrine_Query::create()
        ->select('a.*, b.name AS name, b.identification_number AS dentification_number, b.sex AS sex,
          c.student_id AS student_id, c.grade AS grade, c.class_sn AS class_sn, c.number AS number')
        ->from('Student_Model_StudentTransfer a ')
        ->leftJoin('a.Student_Model_Student  b')
        ->leftJoin('b.Student_Model_StudentSemester c')
        ->where('a.year=c.year AND a.semester=c.semester')
        ->andWhere('c.year=?', $year)
        ->andWhere('c.semester=?',$semester)
        ->andWhereIn('a.causation_kind',array(
        Student_Model_StudentTransfer::DROPOUTS_RETURN,
        Student_Model_StudentTransfer::LEAVE_RETURN,
        Student_Model_StudentTransfer::TRANSFER_RETURN
        ))
        ->orderBy('a.date DESC');

        $res = $q->fetchArray();
        $this->view->data = $res;
    }

    /**
     * 搜尋已調出學生
     * @return unknown_type
     */
    public function reinSearchAction()
    {
        $this->getHelper('layout')->disableLayout();
        $this->getHelper('ViewRenderer')->setNorender();
        //        $causationKind = (int) $this->getRequest()->getParam('selOutKind');
        $str = $this->getRequest()->getParam('q');
        if (!$str)
        echo '';
        else {
            $f = new Zend_Filter_StripTags();
            $str = $f->filter($str);
            $q = Doctrine_Query::create()

            ->select('DISTINCT a.sn, a.student_sn AS student_sn, a.year, a.semester,  c.student_id AS  student_id, b.name AS name')
            ->from('Student_Model_StudentTransfer a')
            ->leftJoin('a.Student_Model_Student b')
            ->leftJoin('b.Student_Model_StudentSemester c')
            ->whereIn('a.causation_kind',
            array(Student_Model_StudentTransfer::REDEPLOYMENT,
            Student_Model_StudentTransfer::DROPOUTS,
            Student_Model_StudentTransfer::ABROAD,
            ))
            ->Where("b.name LIKE '%$str%'")
            ->andWhere('b.study_condition <> 0')
            ->andWhere("a.sn = (SELECT MAX(sn) FROM Student_Model_StudentTransfer  WHERE student_sn=a.student_sn)")
            ->orderBy('a.year DESC, a.semester DESC');
            $res = $q->fetchArray();
            foreach($res as $row)
            echo $row['name'].'('.$row['student_id'] .')|'.$row['sn']."\n";
        }

    }

    /**
     *  取出異動資料
     */
    public function getTransferDataByidAction()
    {
        $sn = (int)$this->getRequest()->getParam('sn');
        $core = new StudentTransfer_Model_Core();
        $res = $core->getTransferDataByid($sn);
        $this->_helper->json($res);
    }

}

